import router, { asyncRouter } from './router'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import getPageTitle from '@/utils/get-page-title'
router.beforeEach(async(to, from, next) => {
  NProgress.start() // 开启进度条
  // console.log(to, 'to')
  document.title = getPageTitle(to.meta.title)
  const whiteList = ['/login', '/404']
  const token = store.state.user.token
  // console.log(token)
  if (token) {
    if (to.path === '/login') {
      // console.log('不能')
      next('/')
      NProgress.done()
    } else {
      // 触发actions中的函数，发送请求获取用户的信息
      // 判断用户信息是否已经获取了，如果已经获取就不要在发请求或取了
      if (!store.state.user.uesrInfo.userId) {
        // 返回页面级别权限数据
        const menus = await store.dispatch('user/getUserInfo')
        // console.log(asyncRouter, 'wwjj')
        // console.log(menus, 'wwj')
        // 筛选用户可以访问的动态路由
        const filterRoutes = asyncRouter.filter(route => {
          return menus.includes(route.children[0].name)
        })
        // console.log(filterRoutes, 'wwj')
        // console.log(router, 'wwj')
        // 动态的添加用户可以访问的路由
        router.addRoutes(filterRoutes)
        store.commit('menu/setMenuList', filterRoutes)
      }
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})
router.afterEach(() => {
  NProgress.done()
})
